/*
    Copyright Pat Niemeyer, 2007
    Derived from example from Pat's book: Learning Java, O'Reilly & Associates
 */
package quickAdd.client;

import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.Node;

import java.util.List;
import java.util.ArrayList;

class DOMUtil
{
    // todo: Element getElementsByTagName is confused by namespaces on Safari
    public static List getElementsByTagName( Element element, String name )
    {
        List list = new ArrayList();
        NodeList children = element.getChildNodes();
        for( int i =0; i<children.getLength(); i++ ) {
            Node child = children.item(i);
            if (child.getNodeName().equals(name))
                list.add( child );
        }
        return list;
    }

    // todo: this version uses our hacked getElementsByTagName
    public static Element getFirstElement( Element element, String name )
    {
        List list = getElementsByTagName( element, name );
        if ( list.size() < 1 )
            throw new RuntimeException(
                "Element: " + element + " does not contain: " + name );
        return (Element)list.get(0);
    }
    //public static Element getFirstElement( Element element, String name )
    //{
    //    NodeList nl = element.getElementsByTagName( name );
    //    if ( nl.getLength() < 1 )
    //        throw new RuntimeException(
    //            "Element: " + element + " does not contain: " + name );
    //    return (Element)nl.item( 0 );
    //}

    public static String getSimpleElementText( Element node, String name )
    {
        Element namedElement = getFirstElement( node, name );
        return getSimpleElementText( namedElement );
    }

    public static String getSimpleElementText( Element node )
    {
        StringBuffer sb = new StringBuffer();
        NodeList children = node.getChildNodes();
        for ( int i = 0; i < children.getLength(); i++ )
        {
            Node child = children.item( i );
            if ( child.getNodeType() == Node.TEXT_NODE )
                sb.append( child.getNodeValue() );
        }
        return sb.toString();
    }

    /**
     * Get the first child element named tagName with the specified attribute value
     * or null.
     */
    public static Element getElementMatching(
        Element parent, String tagName, String attributeName, String attributeValue )
    {
        List elements = getElementsByTagName( parent, tagName );
        for ( int i = 0; i < elements.size(); i++ )
        {
            Element element = (Element)elements.get( i );
            if ( !element.hasAttribute(attributeName ) ) {
                continue;
            }
            if( element.getAttribute(attributeName).equals(attributeValue) )
                return element;
        }

        return null;
    }
}
